package com.gemantic.auth.service.impl;

import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import com.gemantic.auth.model.TokenSession;
import com.gemantic.auth.service.AuthSessionService;
import com.gemantic.auth.service.RedisOperatorService;
import com.gemantic.config.DIYRestTemplate;
import com.google.common.collect.Maps;

@Service
public class AuthSessionServiceImpl implements AuthSessionService{
	
	Logger logger = LoggerFactory.getLogger(AuthSessionServiceImpl.class);
		
	@Autowired
	private RedisOperatorService redisOperatorService;
	
	@Resource
    private DIYRestTemplate restTemplate;

	@Override
	public boolean verify(String userName, String password) {
		// 根据自己数据库数据来校验
		if (userName.equals(password)) {
			return true;
		}
		else {
			return false;
		}
	}
	
	@Override
	public boolean tokenTrans(HttpServletRequest request, String originalUrl,String userName, String token) throws Exception {
		String[] paths = originalUrl.split("/");
		String shortAppServerUrl = paths[2];
		String returnUrl = "http://"+shortAppServerUrl+"/receiveToken?ssoToken="+token+"&userName="+userName;
		//http://peer1:8088/receiveToken?ssoToken=80414bcb-a71d-48c8-bfee-098a303324d4&userName=xixi
		/*Map<String, Object> param = Maps.newHashMap();
		param.put("ssoToken", token);
		param.put("userName", userName);
		ResponseEntity<String> resu = restTemplate.exchange(returnUrl+"?ssoToken={ssoToken}&userName={userName}", HttpMethod.GET, null, new ParameterizedTypeReference<String>() {}, param);*/
		//return "success".equals(resu.getBody());
		return "success".equals(restTemplate.getForObject(returnUrl, Object.class));
	}

	@Override
	public String cacheSession(String userName) {
		//创建token
		String token = UUID.randomUUID().toString();
		redisOperatorService.putUserInfo(userName, token);
		TokenSession tokenSession = new TokenSession(token,userName); 
		redisOperatorService.putTokenInfo(token, tokenSession);
		return token;
	}

	@Override
	public boolean checkAndAddAddress(String token, String address) {
		TokenSession tokenSession = redisOperatorService.getTokenInfo(token);
		logger.info("tokenSession " + tokenSession);
		if(tokenSession!=null) {
			tokenSession.getAddressList().add(address);
			tokenSession.setTokenFlag(true);
			redisOperatorService.putTokenInfo(token, tokenSession);
			return true;
		}
		return false;
	}

	@Override
	public boolean checkUserLoginStatus(String userName,String address) {
		boolean flag = false;
		String token = redisOperatorService.getUserInfo(userName);
		if(token!=null) {
			TokenSession tokenSession = redisOperatorService.getTokenInfo(token);
			if(tokenSession!=null) {
				if(tokenSession.getAddressList().contains(address)) {
					flag =  true;
				}
			}
		}
		return flag;
	}

	@Override
	public String getUserToken(String userName) {
		String token = redisOperatorService.getUserInfo(userName);
		if(token==null) {
			return null;
		}else {
			if(redisOperatorService.getTokenInfo(token)!=null) {
				return token;
			}else {
				return null;
			}
			
		}
	}

	@Override
	public List<String> logoutByUser(String userName) {
		String ssoToken = redisOperatorService.getUserInfo(userName);
		redisOperatorService.deleteUserInfo(userName);
		if(ssoToken!=null) {
			logoutByToken(ssoToken);
		}
		return null;
	}

	@Override
	public List<String> logoutByToken(String ssoToken) {
		if(ssoToken!=null) {
			TokenSession tokenSession = redisOperatorService.getTokenInfo(ssoToken);
			if(tokenSession!=null) {
				redisOperatorService.deleteTokenInfo(ssoToken);
				return tokenSession.getAddressList();
			}
		}
		return null;
	}
	
	@Override
	public void sendLogout2Client(String address,String ssoToken) {
		String returnUrl = "http://"+address+"/ssoDeleteToken?ssoToken="+ssoToken;
		try {
			restTemplate.getForObject(returnUrl, String.class);
		}catch(Exception e) {
			//Log and do nothing
		}
	}
	
}
